import { defineStore } from "pinia";
import { computed, reactive, ref } from "vue";
import { Local } from '@/utils/storage'
import { ADMIN_ACCOUNT, STORE_CONFIG, STORE_TAB_VIEW_CONFIG } from '@/stores/constant/cacheKey'

/** 登录信息 */
export const useUserStore = defineStore('user', () => {
    /** 用户信息 */
    let user = reactive<userModel>({});

    /** 是否已经登录 */
    const isAuth = computed(() => {
        let accessToken = user.accessToken;
        if (!accessToken) {
            accessToken = Local.get(ADMIN_ACCOUNT);
            if (accessToken) {
                user.accessToken = accessToken;
            }
        }

        return accessToken != '';
    })

    /** 设置登录凭据 */
    const setToken = (accessToken: string) => {
        user.accessToken = accessToken;
        Local.set(ADMIN_ACCOUNT, accessToken);
    }

    /** 退出登录 */
    const removeLoginInfo = () => {
        user = {};
        Local.remove(ADMIN_ACCOUNT);
        Local.remove(STORE_CONFIG);
        Local.remove(STORE_TAB_VIEW_CONFIG);
    }

    return { user, isAuth, setToken, removeLoginInfo }
})

/** 用户信息模型 */
interface userModel {
    /** 用户名 */
    name?: string
    /** 头像 */
    avatar?: string
    /** 登录时间 */
    lastLoginTime?: Date
    /** 登录凭据 */
    accessToken?: string
}